# -*- coding: utf-8 -*-
import sys
import os
import time
import win32gui
import win32con
import win32process
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox
from PyQt5.QtCore import Qt
import subprocess

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("外部程序启动器")
        self.setGeometry(100, 100, 300, 200)
        self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        
        self.button = QPushButton("启动外部程序", self)
        self.button.setGeometry(100, 80, 100, 40)
        self.button.clicked.connect(self.start_external_program)
        
        self.process_id = None

    def start_external_program(self):
        if self.process_id is None:
            try:
                script_dir = os.path.dirname(os.path.abspath(__file__))
                exe_path = os.path.join(script_dir, "SMA_stp05.exe")
                
                if not os.path.exists(exe_path):
                    QMessageBox.critical(self, "错误", f"未找到程序: {exe_path}")
                    return
                
                # 使用subprocess启动并保存进程对象
                self.process = subprocess.Popen(
                    [exe_path],
                    cwd=script_dir,
                    creationflags=subprocess.CREATE_NEW_CONSOLE
                )
                self.process_id = self.process.pid
                self.button.setText("停止程序")
                
                # 最小化外部程序窗口
                time.sleep(1)
                self.minimize_exe_window()
                
            except Exception as e:
                QMessageBox.critical(self, "错误", f"启动失败: {str(e)}")
        else:
            # 确保关闭外部程序
            try:
                self.process.terminate()  # 先尝试正常终止
                self.process.wait(2)     # 等待2秒
                if self.process.poll() is None:  # 如果还在运行
                    self.process.kill()  # 强制终止
            except:
                os.system(f'taskkill /f /im SMA_stp05.exe')  # 最终兜底方案
            finally:
                self.process_id = None
                self.button.setText("启动外部程序")

    def minimize_all_windows_except_self(self):
        """最小化除主窗口外的所有窗口"""
        self_hwnd = self.winId().__int__()
        def callback(hwnd, extra):
            if hwnd != self_hwnd and win32gui.IsWindowVisible(hwnd):
                win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
            return True
        
        win32gui.EnumWindows(callback, None)

    def minimize_exe_window(self):
        """最小化外部程序窗口"""
        start_time = time.time()
        while time.time() - start_time < 5:  # 最多等待5秒
            try:
                def callback(hwnd, extra):
                    if win32gui.IsWindowVisible(hwnd):
                        _, pid = win32process.GetWindowThreadProcessId(hwnd)
                        if pid == self.process_id:
                            win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
                            return False
                    return True
                
                win32gui.EnumWindows(callback, None)
                break
            except:
                time.sleep(0.5)  # 等待0.5秒后重试

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())